//
//  LRCommentModel.swift
//  LRWeibo
//
//  Created by 雷路荣 on 15/12/26.
//  Copyright © 2015年 leilurong. All rights reserved.
//

import UIKit

class LRCommentModel: NSObject {
    
    /// 用于显示正在加载数据cell
    var loading = false
    
    /// 评论的ID
    var id: Int = 0
    
    /// 评论创建时间
    var created_at: String?
    
    /// 来源
    var source: String? {
        didSet {
            // 在KVC设置来源之后.我们自己再重新设置来源,再次赋值给source, 在didSet里面设置属性是不会调用属性监视器的
            source = source?.source()
        }
    }
    
    /// 评论作者的用户信息字段
    var user: LRUser?
    
    /// 内容
    var text: String?
    init(loading: Bool) {
        self.loading = loading
        super.init()
    }
    /// 字典转模型
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    /// 有多少个key就会调用多少次该方法
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            if let dict = value as? [String: AnyObject] {
                self.user = LRUser(dict: dict)
            }
            return
        }
        super.setValue(value, forKey: key)
    }
    //防止程序找不到key内容奔溃，找不到什么也不做
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}

    /**
      获取评论数据转模型回调
     */
    class func loadComments(id: Int,since_id: Int, max_id: Int, finished:(comments:[LRCommentModel]?, total_number: Int?, previous_cursor: Int?, next_cursor: Int?, error: NSError?) -> ()){
        LRNetworkTool.sharedNetworkTool.loadComments(id, since_id: since_id, max_id: max_id) { (result, error) -> () in
            if error != nil {
                print("加载评论失败:\(error)")
                finished(comments: nil, total_number: nil, previous_cursor: nil, next_cursor: nil, error: error)
                return
            }
            //print("result=\(result)")
            // 总数量
            let total_number = result?["total_number"] as? Int
            
            // 上一页id
            let previous_cursor = result?["previous_cursor"] as? Int
            
            // 下一页id
            let next_cursor = result?["next_cursor"] as? Int
            // 字典转模型数组
            var comments = [LRCommentModel]()
            // 如果有评论数组，解析转模型  需要强转数组类型 [[String: AnyObject]] 是一个存储[String: AnyObject]类型字典的数组
            if let commentsArr = result?["comments"] as? [[String: AnyObject]] {
                for dict in commentsArr {
                    //字典转模型
                    let comment = LRCommentModel(dict: dict)
                    //存储到数组
                    comments.append(comment)
                }
                //回调
                finished(comments: comments, total_number: total_number, previous_cursor: previous_cursor, next_cursor: next_cursor, error: nil)
            }else {
                finished(comments: nil, total_number: total_number, previous_cursor: previous_cursor, next_cursor: next_cursor, error: nil)
            }
            
            
        }
    }
}
